package cn.zf233.jwtshiro.interceptor;

import cn.zf233.jwtshiro.util.JWTUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by zf233 on 2021/7/12
 */
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String token = request.getParameter("token");
        if (token == null) {
            throw new RuntimeException("token不可以为空");
        }
        try {
            JWTUtil.verify(token);
            return true;
        } catch (TokenExpiredException e) {
            throw new RuntimeException("Token已经过期!!!");
        } catch (SignatureVerificationException e) {
            throw new RuntimeException("签名错误!!!");
        } catch (AlgorithmMismatchException e) {
            throw new RuntimeException("加密算法不匹配!!!");
        } catch (Exception e) {
            throw new RuntimeException("无效token~~");
        }
    }
}
